package top.atcra.rpc.protection.loadBalancer.selector.impl;

import top.atcra.rpc.protection.loadBalancer.selector.ServiceSelector;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 基于轮询的服务选择器
 *
 * @author atcra
 * @date 2025-3-25
 */
public class RoundRobinServiceSelector extends ServiceSelector {
    protected final List<InetSocketAddress> addresses;
    protected final AtomicInteger idx;  // 避免冲突

    public RoundRobinServiceSelector(List<InetSocketAddress> addresses) {
        super(addresses);
        this.idx = new AtomicInteger(-1);
        this.addresses = addresses;
    }

    @Override
    public InetSocketAddress getAddress(Object key) {
        if (idx.get() == addresses.size() - 1) {
            idx.set(0);
        } else {
            idx.incrementAndGet();
        }
        return addresses.get(idx.get());
    }
}
